<template>
    <div class="select_area_wrap" v-loading="pay_over">
        <div class="select_area_header">
            <i class="el-icon-arrow-left" @click="handleBack"></i>
            <p class="select_area_title">填写信息</p>
            <p style="visibility: hidden" class="select_area_submit">保存</p>
        </div>
        <div class="select_area_input">
            <div class="area_input">
                <p>姓名</p>
                <el-input v-model="form.name" placeholder="请输入收货人姓名"></el-input>
            </div>
            <div class="area_input">
                <p>电话</p>
                <el-input v-model="form.phone" placeholder="请输入收货人电话"></el-input>
            </div>
            <div class="area_input">
                <p>所在地区</p>
                <div style="display: flex">
                    <el-input v-model="form.area" placeholder="请选择地区"></el-input>
                    <i style="font-size:25px;align-self: center" class="el-icon-arrow-right"
                       @click="selectCity = true"></i>
                </div>
            </div>
            <div class="area_input">
                <p>详细地址</p>
                <el-input v-model="form.detail_area" placeholder="如道路、街道、门牌号、小区、单元室、楼栋号等"></el-input>
            </div>
            <div class="area_input">
                <p>备注</p>
                <el-input
                        type="textarea"
                        :rows="5"
                        placeholder="可以备注商品的型号、颜色、大小等"
                        v-model="form.note">
                </el-input>
            </div>
            <div class="select_goods_wrap">
                <div v-if="id" class="select_goods_list">
                    <div class="select_goods_logo">
                        <el-image v-if="select_goods_info"
                                  :src="$config.baseUrl + select_goods_info.images[0].file_path"
                                  fit="cover"></el-image>
                    </div>
                    <div class="select_goods_desc">
                        <p>
                            {{select_goods_info && select_goods_info.title}}
                        </p>
                        <p class="select_good_amount">
                            <span v-if="sku_mark">已选{{sku_mark}}</span>
                            <span>x{{buy_quantity}}</span>
                        </p>
                        <p class="select_good_price">¥ {{price}}</p>
                    </div>
                </div>
                <div v-if="!id" class="select_goods_list" v-for="(item,index) in select_goods_info" :key="item.cart_id">
                    <div class="select_goods_logo">
                        <el-image
                                :src="$config.baseUrl + item.goods.images[0].file_path"
                                fit="cover"></el-image>
                    </div>
                    <div class="select_goods_desc">
                        <p>
                            {{item.goods.title}}
                        </p>
                        <p class="select_good_amount">
                            <span v-if="item.sku_mark">已选{{item.sku_mark}}</span>
                            <span>x{{item.quantity}}</span>
                        </p>
                        <p class="select_good_price">¥ {{item.price}}</p>
                    </div>
                </div>
            </div>
            <div class="select_goods_price" v-if="id">
                <p>共计{{buy_quantity}}件</p>
                <p>小计：<span style="color:#FF5B05">{{price * parseInt(buy_quantity)}}</span> 元</p>
            </div>
            <div class="select_goods_price" v-if="!id">
                <p>共计{{allQuantity}}件</p>
                <p>小计：<span style="color:#FF5B05">{{allPrice}}</span> 元</p>
            </div>
        </div>
        <div v-show="selectCity">
            <div class="select_goods_dialog_bg" @click="selectCity = false"></div>
            <select_area @on-handle-city="handleSelectCity"></select_area>
        </div>
        <div class="select_area_bottom">
            <p @click="handleBack">取消</p>
            <p @click="handleCreateOrder">确认</p>
        </div>
    </div>
</template>

<script>

    import select_area from '../../components/select_area'
    import http from '../../libs/http'
    import '../../assets/js/ap'
    // import '../../assets/js/jweixin-1.4.0'
    export default {
        name: 'index',
        components: {select_area},
        data() {
            return {
                openid:"",
                name: '',
                form: {
                    name: '',
                    phone: '',
                    area: '',
                    detail_area: '',
                    note: '',
                },
                buy_quantity: 0,
                price: 0,
                sku_mark: "",
                contact_city: '',
                select_goods_info: null,
                selectCity: false,
                id: "",
                select_all:[],
                coc:'',
                pay_over:false
            }
        },
        mounted(){
            document.body.style.overflow = 'auto'
        },
        created() {
            this.getParams()
            if(!sessionStorage.getItem('openId')){
                this.getCode()
            }
        },
        computed: {
            allQuantity: function () {
                if (!this.id) {
                    let cart_length = this.select_goods_info.length;
                    let quantity = 0
                    for (let i = 0; i < cart_length; i++) {
                        quantity = quantity + this.select_goods_info[i].quantity
                    }
                    return quantity
                }
            },
            allPrice: function () {
                if (!this.id) {
                    let cart_length = this.select_goods_info.length;
                    let price = 0
                    for (let i = 0; i < cart_length; i++) {
                        price = price + (this.select_goods_info[i].price * this.select_goods_info[i].quantity)
                    }
                    return price
                }
            }
        },
        methods: {
            isWeiXin() {
                let ua = window.navigator.userAgent.toLowerCase();
                if (ua.match(/MicroMessenger/i) == "micromessenger") {
                    return true;
                }
                else {
                    return false;
                }
            },
            getCode () { // 非静默授权，第一次有弹框
                if(this.isWeiXin()){
                    const code = this.GetUrlParam('code') // 截取路径中的code，如果没有就去微信授权，如果已经获取到了就直接传code给后台获取openId
                    sessionStorage.getItem('code')
                    const local = window.location.href
                    if (code == null || code === '') {
                        window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + 'wx504b75c5ff0b0b7f' + '&redirect_uri=' + encodeURIComponent(local) + '&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect'
                    } else {
                        this.getOpenId(code) //把code传给后台获取用户信息
                    }
                }

            },
            GetUrlParam(name){
                let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
                let r = window.location.search.substr(1).match(reg)
                if(r != null){
                    return unescape(r[2])
                }else{
                    return null
                }
            },
            getOpenId(code){
                this.apiGet('api/wechat/openid?code=' + code).then((res)=>{
                    if(res){
                        this.openid = res.openid;
                        sessionStorage.setItem('openId',res.openid)
                    }
                })
            },
            getParams() {
                // 取到路由带过来的参数
                this.name = this.$route.query.name;
                this.coc =this.$route.query.coc
                if (this.$route.query.id) {
                    this.id = this.$route.query.id;
                    this.buy_quantity = this.$route.query.sum;
                    this.price = this.$route.query.price;
                    console.log(this.$route.query.price)
                    this.sku_mark = this.$route.query.sku_mark;
                    this.apiGet('api/goods/info/' + this.id).then((res) => {
                        console.log(res)
                        this.select_goods_info = res
                    })
                }
                if (this.$route.query.select_num) {
                    this.select_all = this.$route.query.select_num
                    this.select_goods_info = []
                    this.apiGet('api/cart?shop_id=' + sessionStorage.getItem('shopId')).then((res) => {
                        let length = this.$route.query.select_num.length;
                        let cart_length = res.length;
                        for (let i = 0; i < length; i++) {
                            for (let y = 0; y < cart_length; y++) {
                                if (parseInt(this.$route.query.select_num[i]) === res[y].cart_id) {
                                    this.select_goods_info.push(res[y]);
                                }
                            }
                        }
                        console.log(this.select_goods_info);
                    })
                }

            },
            handleSelectCity(city, id) {
                this.form.area = city;
                this.contact_city = id;
                this.selectCity = false
            },
            handleCreateOrder() {
                if (!this.form.name) {
                    this.$message.error('请输入姓名')
                } else if (!this.form.phone) {
                    this.$message.error('请输入手机号码')
                } else {
                    this.pay_over = true
                    let data = {}
                    if (this.id) {
                        data = {
                            origin: "goods",
                            goods_id: parseInt(this.id),
                            quantity: parseInt(this.buy_quantity),
                            contact_city: this.contact_city,
                            contact_name: this.form.name,
                            contact_phone: this.form.phone,
                            contact_address: this.form.area + this.form.detail_area,
                            remark: this.form.note,
                            task_order_id: parseInt(sessionStorage.getItem('task_order_id')),
                            sku_mark: this.sku_mark
                        }
                    }else{
                        let length = this.select_all.length;
                        let array = [];
                        for(let i = 0;i<length;i++){
                            array.push(parseInt(this.select_all[i]))
                        }
                        data = {
                            origin: "cart",
                            cart_ids:array,
                            contact_city: this.contact_city,
                            contact_name: this.form.name,
                            contact_phone: this.form.phone,
                            contact_address: this.form.detail_area,
                            remark: this.form.note,
                            task_order_id: parseInt(sessionStorage.getItem('task_order_id'))
                        }
                    }
                    this.apiPost('api/order/create', data).then((res) => {
                        console.log(res)
                        if(res){
                            if(!this.isWeiXin()){
                                if(this.coc == "alipypay"){
                                    let payment = {
                                        order_id:res.order_id,
                                        scenes:'mweb',
                                        type:2,
                                        mode:1,
                                    }
                                    this.apiPost('api/order/payment',payment).then((res) => {
                                        console.log(res);
                                        if(res){
                                            window.location.href = "https://openapi.alipay.com/gateway.do?" + res.alipay;
                                            // _AP.pay("https://openapi.alipay.com/gateway.do?" + res.alipay);
                                        }
                                    })
                                }else{
                                    let payment = {
                                        order_id:res.order_id,
                                        scenes:'mweb',
                                        type:2,
                                        mode:1,
                                    }
                                    this.apiPost('api/order/payment',payment).then((res) => {
                                        console.log(res)
                                       /* if(res){
                                            window.location.href = "https://openapi.alipay.com/gateway.do?" + res.alipay;
                                            // _AP.pay("https://openapi.alipay.com/gateway.do?" + res.alipay);
                                        }*/
                                    })
                                }

                            }else{
                                let payment = {
                                    order_id:res.order_id,
                                    scenes: 'jsapi',
                                    openid: this.openid,
                                    type:2,
                                    mode:1,
                                };
                                if(this.openid){
                                    payment.openid = this.openid
                                }else{
                                    payment.openid = sessionStorage.getItem('openId')
                                }
                                this.apiPost('api/order/payment',payment).then((res) => {
                                    console.log(res)
                                    if(res){
                                        this.pay_over = false;
                                        let that = this
                                        let wx = res.wx
                                        WeixinJSBridge.invoke(
                                            'getBrandWCPayRequest', wx,
                                            function (res) {
                                                if (res.err_msg == "get_brand_wcpay_request:ok") {
                                                    // 使用以上方式判断前端返回,微信团队郑重提示：
                                                    //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                                                    that.$message.success('支付成功')
                                                    window.location.href = 'http://produce.jmzhipin.com/download'
                                                } else {
                                                    that.$message.error('支付失败')
                                                }
                                            });
                                    }
                                })
                            }
                        }
                    })


                }
            },
            handleBack() {
                this.$router.push({
                    name: this.name,
                    query: {id: this.id, task_order_id:sessionStorage.getItem('task_order_id')}
                    // name:'index'
                })
            }
        },
        mixins: [http]
    }
</script>

<style lang="stylus">
    .select_area_wrap
        width 100%
        height 100%
        padding-bottom 58px
        position relative

        .select_area_header
            height: 44px;
            font-size: 16px;
            color #333333;
            display flex;
            text-align: center;
            line-height: 44px;
            justify-content space-between
            border-bottom 1px solid #E6E6E6

            .select_area_title
                align-self center

            .select_area_submit
                margin-right 20px
                color: rgba(36, 191, 255, 1);

            i
                align-self center
                padding-left 20px

        .select_area_input
            padding 0 20px
            text-align left

            .area_input
                padding 20px 0 18px 0
                border-bottom 1px solid #cccccc

                p
                    font-size: 14px;
                    margin-bottom 13px
                    color: rgba(77, 77, 77, 1)

                .el-input, .el-textarea
                    .el-input__inner, .el-textarea__inner
                        border none;
                        padding 0

                    .el-input__inner
                        height 30px

            .select_goods_wrap
                padding 25px 20px 0 20px

                .select_goods_list
                    display flex
                    padding-bottom 20px

                    .select_goods_logo
                        align-self center

                        img
                            width 90px
                            height 90px
                            border-radius: 5px;
                            margin-right 12px

                    .select_goods_desc
                        width 100%
                        height 75px
                        align-self center
                        display flex
                        flex-direction column
                        justify-content space-between

                        p:nth-child(1)
                            font-size: 15px;
                            font-weight: bold;
                            color: rgba(0, 0, 0, 1);
                            line-height: 20px;

                        /*margin-bottom 25px*/

                        .select_good_price
                            font-size: 17px;
                            font-weight: 800;
                            color: rgba(255, 91, 5, 1);

                        .select_good_amount
                            width 100%
                            font-size: 13px;
                            color: rgba(204, 204, 204, 1);
                            display flex
                            justify-content space-between

            .select_goods_price
                display flex
                padding 20px 0
                font-size: 12px;
                justify-content space-between

                p:nth-child(1)
                    color: rgba(204, 204, 204, 1);

                p:nth-child(2)
                    color: rgba(51, 51, 51, 1);

        .select_area_bottom
            left 0
            bottom 0;
            width 100%
            height 58px
            display flex
            position fixed;
            text-align center
            background-color white
            border-top 1px solid #3BC7FF

            p
                width 50%;
                height 60px
                line-height 60px
                font-size: 17px;

            p:nth-child(1)
                color: rgba(59, 199, 255, 1);

            p:nth-child(2)
                color: #FFFFFF
                background: rgba(59, 199, 255, 1);

        .select_goods_dialog_bg
            position fixed
            top: 0;
            left 0;
            right 0
            bottom 0;
            width 100%;
            height 100%;
            overflow hidden
            background-color rgba(0, 0, 0, .5);
</style>